package com.zhanggm.springcloud.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhanggm.springcloud.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class AuthFilter extends ZuulFilter {

    private Map<String,Integer> counter = new HashMap<>();

    /**
     * 路由之前过滤
     *
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 多个过滤器的过滤顺序
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否要过滤
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        log.info("AuthFilter:shouldFilter");
        //获取request对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //获得登录时，存储到客户端的token
//        String token = request.getHeader("token");
        String token = request.getParameter("token");
        String referer = request.getHeader("Referer");
        log.info("referer:{}",referer);
        //token为空，执行过滤逻辑
        if (StringUtils.isBlank(token)) {
            return false;
        }
        //放行
        return false;
    }

    /**
     * 过滤逻辑
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        log.info("AuthFilter:run");
        //RequestContext上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //拿到HttpServletResponse
        HttpServletResponse response = currentContext.getResponse();
        //设置false，不进行路由
        currentContext.setSendZuulResponse(false);
        currentContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        //设置返回json值
        try {
            response.setContentType("application/json;charset=utf-8");
            ResponseResult responseResult = ResponseResult.fail(1000, "登录超时");
            response.getWriter().append(JSON.toJSONString(responseResult));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
